package com.hassean.we.admin.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.hassean.we.admin.common.constant.CommonConstant;
import com.hassean.we.admin.common.util.Query;
import com.hassean.we.admin.common.util.R;
import com.hassean.we.admin.common.web.BaseController;
import com.hassean.we.admin.model.entity.TbMessage;
import com.hassean.we.admin.model.entity.TbSimInfo;
import com.hassean.we.admin.model.entity.TbTerminal;
import com.hassean.we.admin.service.HttpClientService;
import com.hassean.we.admin.service.TbMessageService;
import com.hassean.we.admin.service.TbSimInfoService;
import com.hassean.we.admin.service.TbTerminalService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yajun
 * @since 2019-03-29
 */
@Api(description = "短信接口")
@Component
@RestController
@RequestMapping("/tbMessage")
public class TbMessageController extends BaseController {
    @Autowired private TbMessageService tbMessageService;
    @Autowired private TbTerminalService tbTerminalService;
    @Autowired private TbSimInfoService tbSimInfoService;
    @Autowired private HttpClientService httpClientService;
    /**
    * 通过ID查询
    *
    * @param id ID
    * @return TbMessage
    */
    @ApiOperation(value = "通过ID查询短信" ,  notes="通过ID查询短信")
    @GetMapping("/{id}")
    public R<TbMessage> get(@PathVariable Long id) {
        return new R<>(tbMessageService.selectById(id));
    }


    /**
    * 分页查询信息
    *
    * @param params 分页对象
    * @return 分页对象
    */
    @ApiOperation(value = "分页查询短信" ,  notes="分页查询短信")
    @RequestMapping("/page")
    public  R<Map<String, Object>>getTbMessagePage(@RequestParam Map<String, Object> params) {
        params.put(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
        List< Map<String, Object>> resultList = new ArrayList<>();
        Map<String,Object>resultMap = new HashMap<>();
        //状态,类型，
        if (params.get("state")!=null&&!(params.get("state")).equals("")){
            Integer state = Integer.parseInt(params.get("state").toString());
            params.put("state",state);//状态条件查询
        }
        if (params.get("type")!=null&&!(params.get("type")).equals("")){
            Integer type = Integer.parseInt(params.get("type").toString());
            params.put("type",type);//类型条件查询
        }
        if (params.get("type")!=null&&!(params.get("type")).equals("")){
            Integer type = Integer.parseInt(params.get("type").toString());
            params.put("type",type);//类型条件查询
        }
        if (params.get("callingPhone")!=null&&!(params.get("callingPhone")).equals("")){
            String callingPhone = params.get("callingPhone").toString();//主叫电话号码
            params.remove("callingPhone");
            //通过电话号码获取终端
            List<Map<String, Object>> list = tbTerminalService.selectTerminalIdByPhone(callingPhone);
            //获取主叫终端id
            if(!list.isEmpty()){

                params.put("calling_terminal_id",list.get(0).get("terminal_id"));
            }

        }
        if (params.get("passivityPhone")!=null&&!(params.get("passivityPhone")).equals("")){
            String passivityPhone = params.get("passivityPhone").toString();//被叫电话号码
            params.remove("passivityPhone");
            //通过电话号码获取终端
            List<Map<String, Object>> list = tbTerminalService.selectTerminalIdByPhone(passivityPhone);
            //获取被叫终端id
            if(!list.isEmpty()){

                params.put("passivity_terminal_id",list.get(0).get("terminal_id"));
            }

        }
        if (params.get("page")!=null&&!(params.get("page")).equals("")){
            Integer page = Integer.parseInt(params.get("page").toString());
            params.put("page",page);
        }else{
            Integer page = 1;
            params.put("page",page);
        }

        if (params.get("limit")!=null&&!(params.get("limit")).equals("")){
            Integer limit = Integer.parseInt(params.get("limit").toString());
            System.out.println("limit:"+limit);
        }else{
            Integer limit = 10;
            params.put("limit",limit);
        }


        Page<TbMessage> page = tbMessageService.selectPage(new Query<>(params), new EntityWrapper<>());
        for (int i = 0; i <page.getRecords().size() ; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("messageId",page.getRecords().get(i).getMessageId());
            map.put("content",page.getRecords().get(i).getContent());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String addTime = sdf.format(page.getRecords().get(i).getAddTime());
            map.put("addTime",addTime);
            map.put("state",page.getRecords().get(i).getState());
            map.put("setTime",page.getRecords().get(i).getSetTime());
            map.put("type",page.getRecords().get(i).getType());
            map.put("temp",page.getRecords().get(i).getTemp());
            map.put("status",page.getRecords().get(i).getStatus());
            map.put("remark",page.getRecords().get(i).getRemark());
            map.put("advanceText",page.getRecords().get(i).getAdvanceText());
            map.put("advanceDate",page.getRecords().get(i).getAdvanceDate());
            map.put("delFlag",page.getRecords().get(i).getDelFlag());

            Long callingTerminalId = page.getRecords().get(i).getCallingTerminalId();//主叫终端ID
            Long passivityTerminalId = page.getRecords().get(i).getPassivityTerminalId();//被呼终端ID
            if(callingTerminalId!=null){
                TbTerminal callingTerminal =   tbTerminalService.selectById(callingTerminalId);
                if(callingTerminal!=null){
                    map.put("callingTerminal",callingTerminal);//主叫终端
                    Long simInfoId = callingTerminal.getSimInfoId();
                    TbSimInfo tbSimInfo =  tbSimInfoService.selectById(simInfoId);
                    map.put("callingPhone",tbSimInfo.getSimNumber());//主叫电话号码
                }
            }
            if (passivityTerminalId!=null){
                TbTerminal passivityTerminal =   tbTerminalService.selectById(passivityTerminalId);
                if(passivityTerminal!=null){
                    map.put("passivityTerminal",passivityTerminal);//被呼终端
                    Long simInfoId = passivityTerminal.getSimInfoId();
                    TbSimInfo tbSimInfo =  tbSimInfoService.selectById(simInfoId);
                    map.put("passivityPhone",tbSimInfo.getSimNumber());//被叫电话号码
                }
            }
            resultList.add(map);
        }
        resultMap.put("total",page.getTotal());//总条数
        resultMap.put("size",page.getSize());//每一页多少条
        resultMap.put("pages",page.getPages());//总页数
        resultMap.put("curren",page.getCurrent());//起始页
        resultMap.put("resultList",resultList);

        return new R<>(resultMap);
    }


    /**
     * 删除
     * @param id ID
     * @return success/false
     */
    @ApiOperation(value = "删除短信" ,  notes="删除短信")
    @DeleteMapping("/{id}")
    public R<Boolean> delete(@PathVariable Long id) {
        TbMessage tbMessage = new TbMessage();
        tbMessage.setMessageId(id);
        tbMessage.setUpdateTime(new Date());
        tbMessage.setDelFlag(CommonConstant.STATUS_DEL);
        return new R<>(tbMessageService.updateById(tbMessage));
    }

    /**
     * 编辑
     * @param  tbMessage  实体
     * @return success/false
     */
    @ApiOperation(value = "编辑短信" ,  notes="编辑短信")
    @PutMapping
    public R<Boolean> edit(@RequestBody TbMessage tbMessage) {
        tbMessage.setUpdateTime(new Date());
        return new R<>(tbMessageService.updateById(tbMessage));
    }


    /**
     * 测试定时器,每2秒钟执行一次，开启程序时候启动
     */
    @ApiOperation(value = "测试定时器" ,  notes="测试定时器")
    @Scheduled(fixedRate = 2000)
    public void scheduled(){
            //请求外部数据
            System.out.println("我是定时器");


    }

    /**
     * 定时发短信
     */
    @ApiOperation(value = "定时发短信" ,  notes="定时发短信")
    @RequestMapping("/add")
    public   R<Boolean> setTimeAdd(@RequestBody TbMessage tbMessage)throws ParseException {
        Long time = null;
        Long timeInterval = null;
        if(tbMessage.getSetTime()!=null){//有定时
            time = tbMessage.getSetTime().getTime();

            Long nowTime = new Date().getTime();//现在时间戳
            timeInterval = time - nowTime ;//定时设置，线程，被设定的时间减去现在的时间戳
            tbMessage.setState(1);
            tbMessageService.insert(tbMessage);//添加操作
            ThreadsetTime(timeInterval,tbMessage);//定时操作
            return new R<>(true);
        }else{//没有定时
            boolean flag = true;
            if (flag){
                return new R<>(tbMessageService.insert(tbMessage));
            }else{
                return new R<>(false);
            }

        }

    }



    //定时线程发送短信
    public void ThreadsetTime(Long timeInterval,TbMessage tbMessage) {
        Runnable runnable = new Runnable() {
            Boolean flag = true;
            public void run() {
                while (flag) {
                    try {
                        Thread.sleep(timeInterval);
                        System.out.println("我是定时发短信线程!!,我在等待-----");

                         Map<String ,Object> map = null;
                        //httpClientService.pointTOpointSend(tbMessage);//发短信接口
                         Integer  state = Integer.parseInt(map.get("result").toString());
                         if(state==0){
                             flag = false;
                         }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();

    }


    /**
     * 批量定时发短信（接口要修改，目前还不知道怎么发）
     */
    @ApiOperation(value = "批量定时发短信" ,  notes="批量定时发短信")
    @RequestMapping("/addBatchMessage")
    public   R<Boolean> addBatch(@RequestParam  String content,
                                   @RequestParam String setTime,
                                   @RequestParam  String passivityTerminalIds)throws ParseException {

            Long timeInterval = null;
            //将时间转换为时间戳
            String res;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;
            Long ts = null;
            if(!Strings.isNullOrEmpty(setTime)){
                 date = simpleDateFormat.parse(setTime);
                 ts = date.getTime();
                //定时的时间戳
                System.out.println("ts:"+ts);
                Long nowTime = new Date().getTime();//现在时间戳
                System.out.println("nowTime:"+nowTime);
                //有定时
                timeInterval = ts - nowTime ;//定时设置，线程，被设定的时间减去现在的时间戳
                System.out.println("timeInterval:"+timeInterval);
            }

        ThreadsetTimeBatch(timeInterval,content,setTime,passivityTerminalIds);

        return new R<>(true);
    }
    //定时批量发送短信
    public void ThreadsetTimeBatch(Long timeInterval,
                               String content,String setTime,String passivityTerminalIds) throws ParseException {
        String idstr = passivityTerminalIds;
        List<Long> ids = Lists.newArrayList();
        if (idstr.indexOf(",") > -1) {
            String[] strs = idstr.split(",");
            for (String str : strs) {
                if (!Strings.isNullOrEmpty(str)) {
                    ids.add(Long.valueOf(str));
                }
            }
        } else {
            ids.add(Long.valueOf(idstr));
        }
        if(Strings.isNullOrEmpty(setTime)){
            //没有定时

            for (int i = 0; i <ids.size() ; i++) {
                TbMessage tbMessage = new TbMessage();

                Long passivityTerminalId =Long.parseLong(ids.get(i).toString());
                tbMessage.setPassivityTerminalId(passivityTerminalId);
                tbMessage.setContent(content);
                tbMessage.setState(1);//状态,1已发送、2未发送3未读4已读
                //字符串转时间格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if(!Strings.isNullOrEmpty(setTime)){
                    Date date = sdf.parse(setTime);
                    tbMessage.setSetTime(date);
                }

                Boolean flag = true;
                Map<String ,Object> map =  httpClientService.pointTOpointSend(tbMessage);
                Integer  state = Integer.parseInt(map.get("result").toString());
                if (state==0){
                    tbMessageService.insert(tbMessage);//添加操作
                }


            }
        }else{
            //有定时
            Runnable runnable = new Runnable() {
                Boolean flag = true;
                public void run() {
                    while (flag) {
                        try {
                            Thread.sleep(timeInterval);
                            System.out.println("我是测试定时线程!!,我在等待-----");
                            TbMessage tbMessage = new TbMessage();

                            for (int i = 0; i <ids.size() ; i++) {

                                Long passivityTerminalId =Long.parseLong(ids.get(i).toString());
                                tbMessage.setPassivityTerminalId(passivityTerminalId);
                                tbMessage.setContent(content);

                                //字符串转时间格式
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                Date date = sdf.parse(setTime);
                                tbMessage.setSetTime(date);
                                tbMessage.setState(1);//状态,1已发送、2未发送3未读4已读

                                Map<String ,Object> map  =  httpClientService.pointTOpointSend(tbMessage);
                                Integer  state = Integer.parseInt(map.get("result").toString());
                                if (state==0){
                                    tbMessageService.insert(tbMessage);//添加操作
                                }

                            }
                            flag = false;
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                    }
                }
            };
            Thread thread = new Thread(runnable);
            thread.start();
        }


    }
    /**
     * 测试线程定时
     */
    @ApiOperation(value = "测试线程定时" ,  notes="测试线程定时")
    @RequestMapping("/add2")
    public   R<Boolean> setTimeAdd2(@RequestParam  String time)throws ParseException {

        Long timeInterval = null;
        //将时间转换为时间戳
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(time);
        long ts = date.getTime();
        //定时的时间戳
        System.out.println("ts:"+ts);

        Long nowTime = new Date().getTime();//现在时间戳
        System.out.println("nowTime:"+nowTime);
        //有定时
        timeInterval = ts - nowTime ;//定时设置，线程，被设定的时间减去现在的时间戳
        System.out.println("timeInterval:"+timeInterval);
        ThreadsetTime5(timeInterval);

        return new R<>(true);
    }
    //测试定时线程发送短信
    public void ThreadsetTime5(Long timeInterval) {
        Runnable runnable = new Runnable() {
            Boolean flag = true;
            public void run() {
                while (flag) {
                    try {
                        Thread.sleep(timeInterval);
                        System.out.println("我是测试定时线程!!,我在等待-----");
                        flag = false;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();

    }
    //通过电话号码获取终端
    @ApiOperation(value = "通过电话号码获取终端" ,  notes="通过电话号码获取终端")
    @RequestMapping("/getTbTerminalbyPhone")
    public R< List<Map<String, Object>>> getTbTerminalbyPhone(@RequestParam String phone){

        List<Map<String, Object>> list = tbTerminalService.selectTerminalIdByPhone(phone);
        System.out.println("list:"+list);
        System.out.println("id:"+list.get(0).get("terminal_id"));
        return new R<>(list);
    }
    //获取未读且救援短信
    @ApiOperation(value = "获取未读且救援短信" ,  notes="获取未读且救援短信")
    @RequestMapping("/getTbMessagebyHelp")
    public R<List> showTbRescueTeamList(){
        EntityWrapper entity = new EntityWrapper<>();
        entity.eq("state",3);//1已发送、2未发送3未处理，4已处理
       // entity.where("state!=4");//1已发送、2未发送3未处理，4已处理
        entity.eq("type",1);//1救援2其他
        List<TbMessage>selectList =tbMessageService.selectList(entity);
        return  new R<>(selectList);
    }
    //处理未读且救援短信
    @ApiOperation(value = "处理未读且救援短信" ,  notes="处理未读且救援短信")
    @RequestMapping("/disposeTbMessagebyHelp")
    public R<Boolean> disposeTbMessagebyHelp(@RequestBody TbMessage tbMessage) {

        tbMessage.setUpdateTime(new Date());
        tbMessage.setState(4);//1已发送、2未发送3未处理，4已处理
        return new R<>(tbMessageService.updateById(tbMessage));
    }

}
